package com.neusoft.elmboot;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class WebMvcConfig implements Filter {
     /**
     * 过滤器核心方法，用于处理跨域请求（CORS），并控制对不同源的访问权限
     * 
     * @param req    ServletRequest：HTTP 请求对象
     * @param res    ServletResponse：HTTP 响应对象
     * @param chain  FilterChain：用于将请求传递给下一个过滤器或资源
     * @throws IOException      可能抛出的 IO 异常
     * @throws ServletException 可能抛出的 Servlet 异常
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
    
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
    
        String origin = request.getHeader("Origin");
    
        if ("http://localhost:8081".equals(origin) ) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
    
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept");
        response.setHeader("Access-Control-Max-Age", "3600");
    
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
    
        chain.doFilter(req, res);
    }
}